﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using Repository.Core.Interfaces;

namespace Repository.Core.BaseRepository
{
    public abstract class BaseRepository<T> : IRepository<T> where T : class, IDbEntity
    {
        readonly DataContext _context;
        readonly Table<T> _table;

        protected BaseRepository(DataContext context)
        {
            _context = context;
            _table = _context.GetTable<T>();
        }

        public IQueryable<T> GetAll()
        {
            return _table.Select(u => u);
        }

        public void Delete(T item)
        {
            _table.DeleteOnSubmit(item);
            _context.SubmitChanges();
        }

        public void Save(T item)
        {
            if (item.Id <= 0)
            {
                //insert item
                _table.InsertOnSubmit(item);
            }
            else
            {
                //update item
                var oldItem = GetAll().Where(u => u.Id == item.Id).SingleOrDefault();
                if (oldItem == null)
                {
                    throw new ArgumentException("No such row found in DB");
                }
                UpdateItem(oldItem, item);
            }
            _context.SubmitChanges();
        }

        protected abstract void UpdateItem(T oldItem, T item);
    }
}
